import logging
import re
import oabot_model

from waveapi import simplejson as json
from waveapi import events
from waveapi import model
from waveapi import robot
from waveapi import robot_abstract
from waveapi import document
from waveapi import ops
from google.appengine.api import urlfetch
from xml.dom import minidom

def updatetrackwave():
    query = oabot_model.rep_wave_track.all()
    context = model.Context()
    if query:
        for r in query:
            logging.debug("wave id: %s", r.rep_wave_id)
            wave = context.GetWaveById(r.rep_wave_id)
            if wave:
                logging.debug("wave got")
            else:
                logging.debug("couldn't get wave")
                
            url = "http://www.openaustralia.org/rss/mp/"+str(r.rep_member_id)+".rdf"
            res = urlfetch.fetch(url)
            if res.status_code == 200:
                xmldoc = minidom.parseString(res.content)
                for item in xmldoc.getElementsByTagName('item'):
                    try:
                        title = item.getElementsByTagName('title')[0].firstChild.data
                        desc = item.getElementsByTagName('description')[0].firstChild.data
                        link = item.getElementsByTagName('link')[0].firstChild.data
                        date = item.getElementsByTagName('dc:date')[0].firstChild.data
                        
                        if r.rep_wave_check_first == 1:

                            newblip = wave.CreateBlip()
                        else:
                            newblip = wave.CreateBlip()
                            entry_text = title + "\n"
                            entry_text += desc + "\n"
                            entry_text += link + "\n"
                            newblip.GetDocument().SetText(entry_text)
                            
                            r.rep_wave_check_first = 1
                            r.put()                                                    
                    except IndexError, ValueError:
                        pass

if __name__ == '__main__':
    updatetrackwave()